package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/fwhezfwhez/errorx"
	"io/ioutil"
	"net/http"
	"reflect"
	"smart_home/admin/commons"
)

type BaseController struct {
	beego.Controller
}

// @Title ParseData
// @Description 解析数据到结构
func (c *BaseController) ParseData(data interface{}) error {
	if reflect.TypeOf(data).Elem().Kind() != reflect.Struct {
		return errorx.NewFromString("data isn't struct")
	}
	if c.Ctx.Request.Method == http.MethodPut {
		bytes, err := ioutil.ReadAll(c.Ctx.Request.Body)
		if err != nil {
			return errorx.New(err)
		}
		err = json.Unmarshal(bytes, data)
		if err != nil {
			return errorx.New(err)
		}
	} else {
		if err := c.ParseForm(data); err != nil {
			return errorx.New(err)
		}
	}
	return nil
}

// 输出成功
func (c *BaseController) SuccessResponse(data ...interface{}) {
	c.Ctx.Output.SetStatus(200)
	if len(data) > 0 {
		c.Ctx.Output.JSON(data[0], true, false)
	} else {
		c.Ctx.Output.JSON(nil, true, false)
	}
}

// 输出失败
func (c *BaseController) ErrorResponse(err commons.ErrResponse) {
	// 错误码
	c.Ctx.Output.SetStatus(err.HttpStatusCode)
	c.Ctx.Output.JSON(err.Error, true, false)
}
